package chen.yi.component.mysql.check;

import chen.yi.component.common.exception.BizException;
import chen.yi.component.mysql.enums.TableErrorEnums;
import chen.yi.component.mysql.po.FieldPO;
import chen.yi.component.mysql.utils.TableAttrUtils;
import chen.yi.component.mysql.vo.system.FieldTypeVO;
import cn.hutool.core.util.StrUtil;

import java.util.List;

/**
 * 字段属性校验规则
 * @author huat
 **/
public final class FieldCheckUtils extends BaseCheckUtils{
    private FieldCheckUtils() {}
    /**
     * 校验字段是否合法
     * @param fieldPOList
     */
    public static void checkField(final List<FieldPO> fieldPOList) {
        fieldPOList.forEach(fieldPO -> {
            checkFieldName(fieldPO.getFieldName());
            checkFieldType(fieldPO.getFieldType());
            checkComment(fieldPO.getComment());
        });
    }

    /**
     * 校验字段名是否合法
     * @param fieldName 字段名
     */
    private static void checkFieldName(final String fieldName) {
        if (!NAME_PATTERN.matcher(fieldName).matches() || RESERVED_WORDS.contains(fieldName.toUpperCase())) {
            throw new BizException(TableErrorEnums.FIELD_NAME.getCode(), String.format(TableErrorEnums.FIELD_NAME.getMessage(),fieldName));
        }
    }
    /**
     * 校验字段类型是否合法
     * @param fieldType 字段类型
     */
    private static void checkFieldType(final String fieldType) {
        //获取字段类型对象
        FieldTypeVO fieldTypeObj = TableAttrUtils.getFieldType();
        //获取全部value值
        List<String> allTypeValues = fieldTypeObj.getFieldType().stream()
                .flatMap(category -> category.getTypeValue().stream())
                .toList();
        if(!allTypeValues.contains(fieldType)){
            throw new BizException(TableErrorEnums.TABLE_NAME.getCode(), String.format(TableErrorEnums.FIELD_TYPE.getMessage(),fieldType));
        }
    }

    /**
     * 备注校验
     *
     * @param comment 备注内容
     */
    private static void checkComment(String comment) {
        if (StrUtil.isBlank(comment)) {
            throw new BizException(TableErrorEnums.FIELD_COMMENT.getCode(), TableErrorEnums.FIELD_COMMENT.getMessage());
        }
        if (!COMMENT_PATTERN.matcher(comment).matches()) {
            throw new BizException(TableErrorEnums.COMMENT_CONTENT.getCode(), String.format(TableErrorEnums.COMMENT_CONTENT.getMessage(), comment));
        }
    }
}
